import React, {Component} from 'react';
import './App.css';
import list from './list.json'

class App extends Component {
  state = {
    appName: '幸福二选一',
    shaking: false,
    randomResult: null,
    list: list.list,
    // 被选中的list
    resultList: [],
    // 未被选中的list
    targetList: [...list.list]
  };

  componentDidMount() {
    const _self = this;
    window.getList = () => _self.state.resultList.map(item => item.name);
  }

  handleInputChange = (e) => {
    const state = this.state;
    state[e.target.name] = e.target.value;
    this.setState(state);
  };

  timer = null;

  handleToggleShaking = () => {
    const state = this.state;
    state.shaking = !state.shaking;
    this.setState(state);
    if (state.shaking) {
      const _self = this;
      this.timer = setInterval(function () {
        const randomId = Math.floor(Math.random() * _self.state.targetList.length);
        state.randomResult = _self.state.targetList[randomId];
        _self.setState(state);
      }, 50)
    } else {
      clearInterval(this.timer);
      state.resultList.push(state.randomResult);
      state.targetList = state.targetList.filter(
        item => item.id !== state.randomResult.id
      );
      this.setState(state);
    }
  };


  render() {
    return (
      <div className="App" id={'app'}>
        <div className="main">
          <input type="text" id="title" value={this.state.appName} name={'appName'} onChange={this.handleInputChange}/>
          <h1 onClick={this.handleToggleShaking}>
            {!!this.state.randomResult ? `${this.state.randomResult.name}` : '点我,抽他'}
          </h1>
        </div>
        <div className="list-layout">
          <ul className="list">{
            this.state.resultList.map(item =>
              (<li key={item.id}>{`${item.id} ${item.name}`}</li>)
            )
          }</ul>
        </div>
      </div>
    );
  }
}

export default App;
